package chapt03.lstipple;
// StippledLine.java
// Demonstrates line stippling
// OpenGL SuperBible
// Richard S. Wright Jr.
// rwright@starstonesoftware.com

import javax.media.opengl.GL2;

public class StippledLine
{
	// Define a constant for the value of PI
	static float GL_PI = 3.1415f;
	
	// Rotation amounts
	static float xRot = 0.0f;
	static float yRot = 0.0f;
	
	// Setup the rendering state
	protected static void setup(GL2 gl2, int width, int height)
	{
		// Black background
		gl2.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		
		// Set drawing color to green
		gl2.glColor3f(0.0f, 1.0f, 0.0f);
		
		// Enable Stippling
		gl2.glEnable(GL2.GL_LINE_STIPPLE);
	}
	
	// Called to draw scene
	protected static void render(GL2 gl2, int w, int h)
	{
		float nRange = 100.0f;
		
		// Prevent a divide by zero
		if(h == 0)
			h = 1;
		
		// Set Viewport to window dimensions
		gl2.glViewport(0, 0, w, h);
		
		// Reset coordinate system
		gl2.glMatrixMode(GL2.GL_PROJECTION);
		gl2.glLoadIdentity();
		
		// Establish clipping volume (left, right, bottom, top, near, far)
		if(w <= h)
			gl2.glOrtho(-nRange, nRange, -nRange * h / w, nRange * h / w, -nRange, nRange);
		else
			gl2.glOrtho(-nRange * w / h, nRange * w / h, -nRange, nRange, -nRange, nRange);
		
		gl2.glMatrixMode(GL2.GL_MODELVIEW);
		gl2.glLoadIdentity();
		
		float y;                       // Storage for varying Y coordinate
		int factor = 3;                // Stippling factor
		short pattern = 0x5555;        // Save current size
		
		// Clear the window with current clearing color
		gl2.glClear(GL2.GL_COLOR_BUFFER_BIT);
		
		// Save matrix state and do the rotation
		gl2.glPushMatrix();
		gl2.glRotatef(xRot, 1.0f, 0.0f, 0.0f);
		gl2.glRotatef(yRot, 0.0f, 1.0f, 0.0f);
		
		// Step up Y axis 20 units at a time
		for(y = -90.0f; y < 90.0f; y += 20.0f)
		{
			// Reset the repeat factor and pattern
			gl2.glLineStipple(factor, pattern);
			
			// Draw the line
			gl2.glBegin(GL2.GL_LINES);
				gl2.glVertex2f(-80.0f, y);
				gl2.glVertex2f(80.0f, y);
			gl2.glEnd();
			
			factor++;
		}
		
		// Restore tranformations
		gl2.glPopMatrix();
		
		// Flush drawing commands
		gl2.glFlush();
		
	}
}